package com.ycsj.goldmedalnewconcept.common.http;

import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 网络请求的的回调接口实现类,使用反射技术将返回的JSON字符串解析成泛型
 * Created by Administrator on 2018/12/6 0006.
 */

public abstract class HttpCallBack<Result> implements ICallBack {

    @Override
    public void onSuccess(String result) {
        Gson gson = new Gson();
        Class<?> clz = parseClassInfo(this);
        Result objResult = null;
        try {
            objResult = (Result) gson.fromJson(result, clz);
        } catch (Exception e) {
            ToastUtils.showShort("数据解析异常");
        }
        onSuccess(objResult);
    }

    /**
     * 采用反射的方式获取泛型的Clazz
     *
     * @param object
     * @return
     */
    public static Class<?> parseClassInfo(Object object) {
        Type genType = object.getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        return (Class<?>) params[0];
    }

    public abstract void onSuccess(Result result);

}
